//
// Created by WenDaoJiang on 2017/5/10.
// Copyright (c) 2017 文道江. All rights reserved.
//

#import "PlayVibrate.h"
#import "KVStorage.h"

#define PlayVibrate_playing @"PlayVibrate_playing"

void soundCompleteCallback(SystemSoundID sound, void *clientData) {
    AudioServicesRemoveSystemSoundCompletion(sound);
    if ([PlayVibrate shareInstance].playing) {
        [[PlayVibrate shareInstance] performSelector:@selector(_playVibrate) withObject:nil afterDelay:1];
    }
//    NSLog(@"soundCompleteCallback");
}

@implementation PlayVibrate

static PlayVibrate *_instance = nil;
static SystemSoundID shake_sound_male_id = 0;

+ (PlayVibrate *)shareInstance {
    static PlayVibrate *_instance = nil;

    @synchronized (self) {
        if (_instance == nil) {
            _instance = [[self alloc] init];
        }
    }

    return _instance;
}

- (void)playVibrate {
    [KVStorage setKey:PlayVibrate_playing Value:@"PLAY"];
    NSLog(@"playVibrate %@", [KVStorage getValue:PlayVibrate_playing]);
    //NSLog(@"playVibrate");

    [self _playVibrate];

    [self playSound];
}

- (void)_playVibrate {
    AudioServicesAddSystemSoundCompletion(kSystemSoundID_Vibrate, NULL, NULL, soundCompleteCallback, NULL);
    AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
}

- (void)stopPlayVibrate {
    [KVStorage setKey:PlayVibrate_playing Value:@"NONE"];
    NSLog(@"stopPlayVibrate %@", [KVStorage getValue:PlayVibrate_playing]);
    [self stopSound];
    AudioServicesDisposeSystemSoundID(kSystemSoundID_Vibrate);
    AudioServicesRemoveSystemSoundCompletion(kSystemSoundID_Vibrate);
}


- (void)playSound{
    NSString *path = [[NSBundle mainBundle] pathForResource:@"call_ring" ofType:@"mp3"];
    if (path) {
        AudioServicesCreateSystemSoundID((__bridge CFURLRef) [NSURL fileURLWithPath:path], &shake_sound_male_id);
    }
    AudioServicesPlaySystemSound(shake_sound_male_id);
}

- (void)stopSound {
    AudioServicesDisposeSystemSoundID(shake_sound_male_id);
}

- (BOOL)playing {
    NSLog(@"playing %@", [KVStorage getValue:PlayVibrate_playing]);
    id play = [KVStorage getValue:PlayVibrate_playing];
    if (play == nil)return NO;
    return [play isEqualToString:@"PLAY"];

}


@end
